cap log close
log using "$logs/cr-county-leaid-xwalk.log", replace

* update 4/28/2020 - use the seda crosswalk

	use "$raw/seda/seda_crosswalk_v30.dta", clear
	keep leaid_orig countyid16 countyid year has_geo leaidC
	
		tab leaidC if mi(countyid16) // Missing geo/virtual
		drop if mi(countyid16)
		
	duplicates drop
 	
	bys leaid_orig: egen nvals = nvals(countyid)
	egen tag = tag(leaid_orig)
	tab nvals if tag, m // 98% 
	drop nvals
	
		// Do all have countyid 16?
		gen temp = !mi(countyid16)
		bys leaid_orig: egen max = max(temp)
		assert max == 1
		drop max temp
		
		bys leaid_orig: egen nvals = nvals(countyid16)
		tab nvals if tag // 99%
		
		// Take most recent countyid16
		gsort leaid_orig -year
		collapse (firstnm) countyid16, by(leaid_orig)
		rename leaid_orig leaid
		
	destring leaid countyid, replace
	rename countyid countyid
	tostring countyid, gen(fips)
	replace fips = substr(fips,1,1) if length(fips)==4
	replace fips = substr(fips,1,2) if length(fips)==5
	destring fips, replace
	statastates, fips(fips)
	rename state_name state
	drop state_abb _merge
	save "$data/county_leaid_xwalk.dta", replace
	
log close
